const axios = require('axios')
const querystring = require('query-string')

const baseUrl = 'https://cnodejs.org/api/v1'

module.exports = function(req, res, next) {
  const path = req.path
  const user = req.session.user || { }  // #2 防止undfine产生报错
  const needAccessToken = req.query.needAccessToken // #1

  if (needAccessToken && !user.accessToken) {
    res.status(401).send({
      success: false,
      msg: 'need login'
    })
  }

  const query = Object.assign({}, req.query, {
    accesstoken: (needAccessToken && req.method === 'GET') ? user.accessToken : ''
  })

  if (query.needAccessToken) delete query.needAccessToken // #3 干掉web服务器和client之间的私自定义的参数

  console.log(`accessToken：${user.accessToken}`)
  console.log(`request：${baseUrl}${path}`)

  axios(`${baseUrl}${path}`, {
    method: req.method,
    params: query,
    data: querystring.stringify(Object.assign({}, req.body, {
      accesstoken: (needAccessToken && req.method === 'POST') ? user.accessToken : ''  // #4 所有POST请求都加accessToken
    })),
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded' // #5 指定使用form-data格式发送请求-由于服务端设定导致的
    }
  }).then((resp) => {
    if (resp.status === 200) {
      res.status(resp.status).send(resp.data)
    } else {
      res.status(resp.status).send(resp.data) // #6 链式调用，给client返回错误信息
    }
  }).catch((err) => {
    if (err.response) {
      res.status(500).send(err.response.data)
    } else {
      res.status(500).send({
        success: false,
        msg: '未知错误'
      })
    }
  })
}
